package com.ebraga.trackerclub.android.handler.core;

import android.content.Context;

import com.ebraga.trackerclub.android.exception.BackofficeDBConnectionException;
import com.ebraga.trackerclub.android.exception.dao.BackofficeWebServicesException;
import com.ebraga.trackerclub.android.exception.handler.BackofficeHandlerException;
import com.ebraga.trackerclub.android.exception.manager.BackofficeInvalidSessionManagerException;
import com.ebraga.trackerclub.android.exception.manager.BackofficeManagerException;
import com.ebraga.trackerclub.android.handler.api.SyncDataHandler;
import com.ebraga.trackerclub.android.manager.api.SyncDataManager;
import com.ebraga.trackerclub.android.util.DLog;

public abstract class SyncDataHandlerImpl implements SyncDataHandler {

	private SyncDataManager syncDataManager;
	private Context context;
	
	protected void setSyncDataManager(SyncDataManager syncDataManager) {
		this.syncDataManager = syncDataManager;
	}
	
	public void setContext(Context context) {
		this.context = context;
	}	
	
	@Override
	public void doSync() throws BackofficeHandlerException {
		try {
			if(syncDataManager.isTimeToSyncData()) {
				syncDataManager.syncParameters();
				syncDataManager.syncData();
				syncDataManager.syncRanking();
			}
			
		} catch (BackofficeInvalidSessionManagerException e) {
			DLog.e(e);
			throw new BackofficeHandlerException("Sessão inválida", e);
			
		} catch (BackofficeManagerException e) {
			DLog.e(e);
			throw new BackofficeHandlerException("Erro inesperado", e);
			
		} catch (BackofficeDBConnectionException e) {
			DLog.e(e);
			throw new BackofficeHandlerException("Erro na comunicação com banco local", e);
			
		} catch (BackofficeWebServicesException e) {
			DLog.e(e);
			throw new BackofficeHandlerException("Erro na comunicação com web service", e);
		}
	}

}
